package com.service.admin.admin.controller;

import com.service.admin.support.ProjectProperty;
import com.service.admin.utils.IpAddressUtil;
import com.service.dao.constants.ConfigConstants;
import com.service.admin.admin.controller.request.LoginReq;
import com.service.admin.admin.controller.request.UserModifyInfoReq;
import com.service.admin.admin.controller.request.UserModifyPwdReq;
import com.service.admin.admin.controller.response.UserInfoRep;
import com.service.admin.admin.service.SysUserService;
import com.service.admin.admin.service.SysConfigService;
import com.service.admin.support.SessionUtil;
import com.service.core.exception.CommonException;
import com.service.core.rest.BaseController;
import com.service.core.rest.response.BaseResponse;
import com.service.core.rest.response.OneResponse;
import com.service.dao.model.SysConfig;
import com.service.utility.common.PictureValidationCodeUtil;
import com.service.utility.common.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * <dl>
 * <dt>back-end</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年08月01日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Api(tags = "登录相关")
@RestController
@RequestMapping("/admin")
public class AdminLoginController extends BaseController {
    @Autowired
    private SessionUtil sessionUtil;

    @Autowired
    private Environment environment;

    @Autowired
    private ProjectProperty projectProperty;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysUserService adminUserService;

    @PostMapping("/login")
    @ApiOperation("登录接口")
    public OneResponse login(@ApiParam @RequestBody @Validated LoginReq loginReq, HttpServletRequest request) {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", loginReq, uuid);

//        verifyPicCode(loginReq.getPicCodeId(), loginReq.getPicCode(), uuid);

        loginReq.setLastLoginIp(IpAddressUtil.get(request));
        loginReq.setLastIpRegion(request.getRemoteHost());
        loginReq.setSessionId(request.getSession().getId());
        UserInfoRep result = adminUserService.doLogin(loginReq);
        log.info("请求结束： UUID:{}", uuid);
        return successQueryOneResponse(result);
    }

    private void verifyPicCode(String picCodeId, String picCode, String uuid) {
        SysConfig sysConfig = sysConfigService.getByName(ConfigConstants.IMAGE_VERIFY_CODE_ADMIN);

        if (ObjectUtils.isEmpty(sysConfig) || !StringUtils.equals("1", sysConfig.getConfValue())) {
            return;
        }

        if (StringUtils.isBlank(picCode) || StringUtils.isBlank(picCodeId)) {
            throw new CommonException("图片验证码不能为空");
        }

        String URL = projectProperty.getKaptchaServiceBaseUrl() + "/kaptcha/validate";
        try {
            PictureValidationCodeUtil.validatePictureValidationCode(URL, picCodeId, picCode, uuid);
        } catch (Exception e) {
            throw new CommonException("图片验证码错误");
        }
    }


    private void verifyTwoFaCode(String twoFaCode,String uuid){

    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public BaseResponse logout() {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", "", uuid);
        sessionUtil.removeSession();
        log.info("请求结束： UUID:{}", uuid);
        return successSaveBaseResponse();
    }

    @ApiOperation("修改密码")
    @PostMapping("/modify-pwd")
    public BaseResponse modifyPwd(@ApiParam @RequestBody @Validated UserModifyPwdReq modifyPwdReq) {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", modifyPwdReq, uuid);
        userService.modifyPwd(modifyPwdReq);
        log.info("请求结束： UUID:{}", uuid);
        return successSaveBaseResponse();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/modify-user")
    public BaseResponse modifyUserInfo(@ApiParam @RequestBody @Validated UserModifyInfoReq modifyInfoReq) {
        String uuid = UUIDUtil.randomUUID();
        log.info("请求开始 Msg: 请求参数：{}，UUID:{}", modifyInfoReq, uuid);
        modifyInfoReq.setId(sessionUtil.getUser().getId());
        userService.updateUserInfoBySession(modifyInfoReq);
        log.info("请求结束： UUID:{}", uuid);
        return successSaveBaseResponse();
    }


}
